﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;

namespace space_scavenger
{
    public class ScreenManager : DrawableGameComponent
    {
        ContentManager content;
        IGraphicsDeviceService graphicsDeviceService;
        SpriteBatch spriteBatch;
        Stack<Screen> screenStack;
        InputState inputState;


        //Common stuff for screens
        new public Game Game
        {
            get { return base.Game; }
        }

        new public GraphicsDevice GraphicsDevice
        {
            get { return base.GraphicsDevice; }
        }

        public ContentManager Content
        {
            get { return content; }
        }

        public SpriteBatch SpriteBatch
        {
            get { return spriteBatch; }
        }

        public Stack<Screen> Screens
        {
            get { return screenStack; }
        }

        public InputState InputState
        {
            get { return inputState; }
        }


        public ScreenManager(Game game)
            : base(game)
        {
            screenStack = new Stack<Screen>();
            content = new ContentManager(game.Services, "Content");

            graphicsDeviceService = (IGraphicsDeviceService)game.Services.GetService(
                                                        typeof(IGraphicsDeviceService));

            inputState = InputState.getInstance();

            if (graphicsDeviceService == null)
                throw new InvalidOperationException("No graphics device service.");
        }

        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
        }

        public override void Draw(GameTime gameTime)
        {
            screenStack.Peek().Draw(spriteBatch, gameTime);
        }

        public override void Update(GameTime gameTime)
        {
            inputState.Update(gameTime);
            screenStack.Peek().Update(gameTime);
            if (inputState.checkCommand(InputState.Commands.__DEBUG__SAVE_KEYS))
            {
                inputState.saveConfig();
            }
        }

        public void AddScreen(Screen screen)
        {
            screen.Manager = this;
            screen.Init();
            screenStack.Push(screen);
            
        }

        public void RemoveCurrentScreen()
        {
            screenStack.Peek().Destroy();
            screenStack.Pop();
        }

        protected override void UnloadContent()
        {
            content.Unload();
            while (screenStack.Count > 0)
            {
                RemoveCurrentScreen();
            }
        }
    }
}
